package com.qiangesoft.ip.controller;

import com.qiangesoft.ip.model.Region;
import com.qiangesoft.ip.util.Ip2regionUtil;
import com.qiangesoft.ip.util.IpPconlineUtil;
import net.dreamlu.mica.ip2region.core.Ip2regionSearcher;
import net.dreamlu.mica.ip2region.core.IpInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * IpController
 *
 * @author qiangesoft
 * @date 2024-02-01 15:48:58
 */
@RestController
@RequestMapping("/ip")
public class IpController {

    @Autowired
    private Ip2regionSearcher ip2regionSearcher;

    @GetMapping("/mica")
    public Region mica(String ip) {
        long start = System.currentTimeMillis();

        IpInfo ipInfo = ip2regionSearcher.memorySearch(ip);
        Region region = new Region();
        region.setCountry(ipInfo.getCountry());
        region.setProvince(ipInfo.getProvince());
        region.setCity(ipInfo.getCity());
        region.setIsp(ipInfo.getIsp());

        long end = System.currentTimeMillis();
        System.out.println("接口mica耗时为：" + (end - start));
        return region;
    }

    @GetMapping("/ip2region")
    public Region ip2region(String ip) {
        long start = System.currentTimeMillis();

        String address = Ip2regionUtil.getIp2region(ip);
        String[] split = address.split("\\|");
        Region region = new Region();
        region.setCountry(split[0]);
        region.setProvince(split[2]);
        region.setCity(split[3]);
        region.setIsp(split[4]);

        long end = System.currentTimeMillis();
        System.out.println("接口ip2region耗时为：" + (end - start));
        return region;
    }

    @GetMapping("/third")
    public Region third(String ip) {
        long start = System.currentTimeMillis();

        String address = IpPconlineUtil.getAddress(ip);
        String[] split = address.split("\\|");
        Region region = new Region();
//        region.setCountry(split[0]);
        region.setProvince(split[0]);
        region.setCity(split[1]);
        region.setIsp(split[2]);

        long end = System.currentTimeMillis();
        System.out.println("接口third耗时为：" + (end - start));
        return region;
    }
}
